package com.eight.cloud.mybatisplus.handler;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.eight.cloud.core.global.model.BaseUser;
import com.eight.cloud.core.utils.supply.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import java.time.LocalDateTime;

import static com.eight.cloud.core.global.constant.NumConstant.ONE;
import static com.eight.cloud.core.global.constant.NumConstant.ZERO;
import static com.eight.cloud.core.global.constant.StrConstant.DASH;
import static com.eight.cloud.core.global.constant.StrConstant.EMPTY;

/**
 * 自动填充
 *
 * @ClassName: MpMetaObjectHandler
 * @Author: TXC
 * @Date: 2024-10-05 22:02
 **/
@Slf4j
@AutoConfiguration
public class MpMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "uuid", String.class, UUID.fastUUID().toString().replace(DASH, EMPTY));
        BaseUser loginUser = UserContext.getUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            autoInsert(metaObject, loginUser.getUuid(), loginUser.getDeptId(), loginUser.getTenantId());
        }
        this.strictInsertFill(metaObject, "deleted", Integer.class, ZERO);
        this.strictInsertFill(metaObject, "status", Integer.class, ONE);
    }

    private void autoInsert(MetaObject metaObject, String uuid, String deptId, String tenantId) {
        this.strictInsertFill(metaObject, "updateBy", String.class, uuid);
        this.strictInsertFill(metaObject, "createBy", String.class, uuid);
        // 判断字段是否存在
        boolean fieldExists = metaObject.hasSetter("deptId");
        if (fieldExists) {
            this.strictInsertFill(metaObject, "deptId", String.class, deptId);
        }
        boolean tenantIdExists = metaObject.hasSetter("tenantId");
        if (tenantIdExists) {
            this.strictInsertFill(metaObject, "tenantId", String.class, tenantId);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        BaseUser loginUser = UserContext.getUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, UserContext.getUser().getUuid());
        }
    }
}
